<template>
  <div>
    <div class="deepBackground">
      <!--      任务信息可视化展示-->
      <div
          style="background-color: white; display: flex;flex-direction: column;align-items: center;border-radius: 5px;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);margin: 12px;width: 24%;height: 97%;">
        <div
            style="width: 80%; display: flex; align-items: center;justify-content: center; flex-direction: column;margin-top: 12px;margin-bottom:6px; height: 27% ;background-color: white ;border-radius: 6px;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);"
            id="gauge"
        >
        </div>

        <div
            style="padding: 10px; flex-direction: column;width: 80%; display: flex; align-items: center;justify-content: center; margin: 6px;height: 27% ;background-color: white ;border-radius: 6px;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);"
            id="line"
        >
        </div>

        <div
            style="flex-direction: column;width: 80%;display: flex; align-items: center;justify-content: center;margin: 6px;height: 39% ;background-color: white ;border-radius: 6px;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);"
            id="pie"
        >

        </div>

      </div>


      <!--      任务详细信息表格和查询-->
      <div
          style="display: flex;flex-direction: column;align-items: center;border-radius: 5px;;width: 76%;height: 97%;margin-right: 12px">
        <!--        查询条件区域-->
        <div
            style=" padding: 6px; background-color: white;display: flex;flex-direction: column;align-items: center;width: 100%;height: 20%;margin-right: 12px;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);">
          <!--          任务完成展示数据-->
          <div style="display: flex;align-items: center;justify-content: center;width: 100%; height: 60%">
            <!--            待办任务数-->
            <div style="display: flex;flex-direction: column;align-items: center;justify-content: center;width: 30%">
              <span style="font-family: 'PingFang SC';font-size: 12px;color: darkgray">
                我的待办任务（个）
              </span>
              <span style="font-family: 'PingFang SC';font-size: 16px;margin-top: 8px">
                <el-tag size="medium" type="danger">{{ this.taskStatistics.myToDoTasksNum }}</el-tag>
              </span>
            </div>
            <el-divider direction="vertical"></el-divider>
            <!--            已完成任务总数-->
            <div style="display: flex;flex-direction: column;align-items: center;justify-content: center;width: 30%">
              <span style="font-family: 'PingFang SC';font-size: 12px;color: darkgray">
                我已完成任务总数（个）
              </span>
              <span style="font-family: 'PingFang SC';font-size: 16px;margin-top: 8px">
                <el-tag size="medium" type="success">{{ this.taskStatistics.myAllDoneTaskNum }}</el-tag>
              </span>
            </div>
            <el-divider direction="vertical"></el-divider>
            <!--            本周完成的任务数-->
            <div style="display: flex;flex-direction: column;align-items: center;justify-content: center;width: 30%">
               <span style="font-family: 'PingFang SC';font-size: 12px;color: darkgray">
                我本周完成总数（个）
              </span>

              <span style="font-family: 'PingFang SC';font-size: 16px;margin-top: 8px">
                <el-tag size="medium">{{ this.taskStatistics.weekDoneTaskNum }}</el-tag>
              </span>
            </div>
          </div>
          <el-divider></el-divider>
          <!--          任务查询展示数据-->
          <div style="display: flex;align-items: center;justify-content: center;width: 100%; height: 40%">
            <div style="width: 30%; display: flex;align-items: center;justify-content: center">
              <span style="font-weight: bolder;font-family: 'PingFang SC';font-size: 12px;margin: 6px">所属项目:</span>
              <el-select v-model="projectSelectValue" placeholder="请选择所属项目">
                <el-option
                    v-for="item in projectOptions"
                    :key="item.projectId"
                    :label="item.projectName"
                    :value="item.projectId">
                </el-option>
              </el-select>

            </div>

            <div style="width: 30%; display: flex;align-items: center;justify-content: center">
              <span style="font-weight: bolder;font-family: 'PingFang SC';font-size: 12px;margin: 6px">任务类型:</span>
              <el-select v-model="taskTypeSelectValue" placeholder="请选择任务类型">
                <el-option
                    v-for="item in taskTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </div>

            <div style="width: 30%; display: flex;align-items: center;justify-content: center">
              <span style="font-weight: bolder;font-family: 'PingFang SC';font-size: 12px;margin: 6px">任务级别:</span>
              <el-select v-model="taskPrioritySelectValue" placeholder="请选择任务级别">
                <el-option
                    v-for="item in taskPriorityOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </div>

            <div style="width: 30%; display: flex;align-items: center;justify-content: center">
              <el-button type="primary" style="width: 37%;margin: 12px" @click="taskConditionalQueryByPage">搜索
              </el-button>
              <el-button style="width: 37%;margin: 12px" @click="conditionReset">重置
              </el-button>
            </div>
          </div>

        </div>
        <!--      表格显示区域-->
        <div
            style="background-color: white;display: flex;flex-direction: column;align-items: center;border-radius: 5px;;width: 100%;height: 80%;margin-right: 12px; margin-top:6px;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);">
          <div style="display: flex;align-items: center;justify-content: center;height: 10%;margin: 6px;width: 100%">
            <div style="display: flex;align-items: center;justify-content: left;width: 50%">
              <Span style="font-size: 24px;font-family: 'PingFang SC';font-weight: bolder;margin-left: 12px">任务汇总</Span>
            </div>
            <div style="display: flex;align-items: center;justify-content: center;width: 50%">
              <!--              任务状态选择-->
              <el-radio-group v-model="tabPosition">
                <el-radio-button label="all" @click.native="changeTab('all')">全部</el-radio-button>
                <el-radio-button label="done" @click.native="changeTab('done')">已完成</el-radio-button>
                <el-radio-button label="undo" @click.native="changeTab('undo')">未完成</el-radio-button>
                <el-radio-button label="handUp" @click.native="changeTab('handUp')">挂起</el-radio-button>

              </el-radio-group>
              <!--              任务模糊查询-->
              <el-input
                  placeholder="请选择任务id或者名称"
                  v-model="searchValue" style="width: 37%;margin-left: 20px;margin-right: 12px">
              </el-input>
              <el-button type="primary" icon="el-icon-search" @click="selectTaskByIdOrName">搜索</el-button>

            </div>
          </div>
          <el-table
              :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
              style="width: 98%">
            <el-table-column
                label="任务Id"
                prop="taskId">
            </el-table-column>

            <el-table-column
                label="任务名称"
                prop="taskName">
            </el-table-column>

            <el-table-column
                label="所属项目"
                prop="projectId">
              <!--              <template slot-scope="scope3">
                         {{escapeProjectNameById(row.projectId)}}
                            </template>-->
            </el-table-column>

            <el-table-column
                label="优先级"
                prop="taskPriority">
              <template slot-scope="scope">
                <el-tag
                    :type="switchTaskPriority(scope.row.taskPriority).tagStyle"
                    disable-transitions
                    effect="dark"
                >{{ switchTaskPriority(scope.row.taskPriority).priorityName }}
                </el-tag>

              </template>
            </el-table-column>

            <el-table-column
                label="任务类型"
                prop="taskStatus">

              <template slot-scope="scope1">
                <el-tag
                    type="info"
                    effect="plain"
                    disable-transitions>
                  <i :class="switchTaskType(scope1.row.taskType).iconStyle"></i>
                  {{ switchTaskType(scope1.row.taskType).typeName }}
                </el-tag>
              </template>

            </el-table-column>

            <el-table-column
                label="当前状态"
                prop="taskStatus">
              <template slot-scope="scope2">
                <el-tag
                    hit="false"
                    :color="switchTaskStatus(scope2.row.taskStatus).color"
                    disable-transitions
                    effect="dark"
                >{{ switchTaskStatus(scope2.row.taskStatus).statusName }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column
                label="操作"
                align="center"
            >
              <template slot-scope="scope">
                <el-button
                    size="mini"
                    @click="viewTaskDetails(scope.row.taskId)">查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="display: flex;align-items: center;justify-content: center;margin: 6px">
            <el-pagination
                class="pagination"
                background
                layout="prev, pager, next"
                :pageSize="pageSize"
                :total="total"
                @current-change="change"
            >
            </el-pagination>
          </div>
        </div>
      </div>


    </div>
  </div>
</template>

<script>
//引入echarts图表
import * as echarts from 'echarts';
import MyTasks from './MyTasks.vue';


//echarts图标的option展示的数据

//任务完成类型饼图
const option = {
  tooltip: {
    trigger: 'item'
  },
  legend: {
    top: '5%',
    left: 'center'
  },
  series: [
    {
      name: '总体任务完成类型',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 40,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        {value: 4, name: '低级', itemStyle: {color: '#c4c4c4'}},
        {value: 15, name: '中级', itemStyle: {color: 'rgb(64, 158, 255)'}},
        {value: 12, name: '高级', itemStyle: {color: 'rgb(238, 102, 102)'}},
        {value: 16, name: '紧急', itemStyle: {color: 'rgb(250, 200, 88)'}}
      ]
    }
  ]
}

//任务完成次数折线图
const option1 = {
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['低', '中', '高', '紧急']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '低',
      type: 'line',
      stack: 'Total',
      data: [0, 0, 0, 0, 0, 0, 0, 0],
      lineStyle: {
        color: '#c0c0c0'
      },
      itemStyle: {
        normal: {
          color: '#c0c0c0'
        }
      }
    },
    {
      name: '中',
      type: 'line',
      stack: 'Total',
      data: [0, 0, 0, 0, 0, 0, 0, 0],
      lineStyle: {
        color: 'rgb(64, 158, 255)'
      },
      itemStyle: {
        normal: {
          color: 'rgb(64, 158, 255)'
        }
      }
    },
    {
      name: '紧急',
      type: 'line',
      stack: 'Total',
      data: [0, 0, 0, 0, 0, 0, 0, 0],
      lineStyle: {
        color: 'rgb(230, 162, 60)'
      },
      itemStyle: {
        normal: {
          color: 'rgb(230, 162, 60)'
        }
      }
    },
    {
      name: '高',
      type: 'line',
      stack: 'Total',
      data: [0, 0, 0, 0, 0, 0, 0, 0],
      lineStyle: {
        color: 'rgb(245, 108, 108)'
      },
      itemStyle: {
        normal: {
          color: 'rgb(245, 108, 108)'
        }
      }
    },

  ]
}

//绩效评分图
const option2 = {
  series: [
    {
      type: 'gauge',
      startAngle: 180,
      endAngle: 0,
      center: ['50%', '75%'],
      radius: '90%',
      min: 0,
      max: 1,
      splitNumber: 8,
      axisLine: {
        lineStyle: {
          width: 4,
          color: [
            [0.25, '#FF6E76'],
            [0.5, '#FDDD60'],
            [0.75, '#58D9F9'],
            [1, '#7CFFB2']
          ]
        }
      },
      pointer: {
        icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
        length: '12%',
        width: 8,
        offsetCenter: [0, '-60%'],
        itemStyle: {
          color: 'auto'
        }
      },
      axisTick: {
        length: 12,
        lineStyle: {
          color: 'auto',
          width: 2
        }
      },
      splitLine: {
        length: 20,
        lineStyle: {
          color: 'auto',
          width: 5
        }
      },
      axisLabel: {
        color: '#464646',
        fontSize: 12,
        distance: -60,
        rotate: 'tangential',
        formatter: function (value) {
          if (value === 0.875) {
            return 'Grade A';
          } else if (value === 0.625) {
            return 'Grade B';
          } else if (value === 0.375) {
            return 'Grade C';
          } else if (value === 0.125) {
            return 'Grade D';
          }
          return '';
        }
      },
      title: {
        offsetCenter: [0, '-10%'],
        fontSize: 18
      },
      detail: {
        fontSize: 30,
        offsetCenter: [0, '-35%'],
        valueAnimation: true,
        formatter: function (value) {
          return Math.round(value * 100) + '';
        },
        color: 'inherit'
      },
      data: [
        {
          value: 0,
          name: '绩效'
        }
      ]
    }
  ]
};
export default {
  name: "TaskSummary",
  components: {
    MyTasks
  },
  data() {
    return {
      loginUser: JSON.parse(localStorage.getItem("loginUser")), //当前登录用户
      tableData: [],//任务表的绑定数据

      selectProject: '',//查询条件选择的项目名称
      projectOptions: [],//后端查询返回的所有项目

      taskTypeOptions: [  //任务类型查询条件选择
        {
          value: '0',
          label: 'Bug'
        },
        {
          value: '1',
          label: '需求开发'
        },
        {
          value: '2',
          label: '其他'
        },
        {
          value: '3',
          label: '优化'
        },
        {
          value: '4',
          label: '测试'
        },
      ],
      taskPriorityOptions: [
        {
          value: '0',
          label: '低'
        },
        {
          value: '1',
          label: '中'
        },
        {
          value: '2',
          label: '高'
        },
        {
          value: '3',
          label: '紧急'
        },
      ],


      //任务汇总各种数据统计封装类
      taskStatistics: {
        myToDoTasksNum: 0, //待办任务数
        myAllDoneTaskNum: 0,//已完成的所有任务数
        weekDoneTaskNum: 0,//本周完成的任务数
        personalPerformance: 0,//个人绩效
        allTaskPriorityNum: [], //当前用户完成的所有任务的优先级分布
        weekTaskPriorityNum: [],//当前用户完成的本周的任务的优先级分布
      },
      //分页相关
      pageSize: 7, //设置默认值为12条一页
      total: 0,
      pageNum: 0,

      tabPosition: 'all',//任务状态的表格显示

      projectSelectValue: '',  //项目查询条件
      taskTypeSelectValue: '', //任务类型查询条件
      taskPrioritySelectValue: '',//任务优先级查询条件

      searchValue: '' //模糊查询绑定的数据


    }
  },
  mounted() {
    //页面元素加载完成后，进行对echarts的加载

    //饼图
    var pieDom = document.getElementById('pie');
    var pieChart = echarts.init(pieDom);

    //折现图
    var lineDom = document.getElementById('line');
    var lineChart = echarts.init(lineDom);


    //仪表图
    var gaugeDom = document.getElementById('gauge');
    var gaugeChart = echarts.init(gaugeDom);


    //获取展示的任务相关图表数据
    this.$request.get("/task/gettaskStatistics", {
      params: {
        userId: this.loginUser.uid
      }
    }).then(res => {
      if (res.successFlag) {
        this.taskStatistics = res.data
        //设置一下图表数据和后端数据的绑定

        //1.绑定绩效
        option2.series[0].data[0].value = this.taskStatistics.personalPerformance
        gaugeChart.setOption(option2)


        //2.绑定饼图
        let allTaskPriorityNum = this.taskStatistics.allTaskPriorityNum;
        // 定义任务优先级对应的颜色映射关系
        const priorityColorMap = {
          '低级': '#c4c4c4',
          '中级': 'rgb(64, 158, 255)',
          '高级': 'rgb(238, 102, 102)',
          '紧急': 'rgb(250, 200, 88)'
        };

        //构建数据 并且能根据类型匹配对应颜色样式
        const showData = Object.keys(allTaskPriorityNum).map(key => ({
          value: allTaskPriorityNum[key],
          name: key,
          itemStyle: {
            // 这里你可以根据需要设置颜色等样式
            color: priorityColorMap[key]
          }
        }));
        option.series[0].data = showData
        pieChart.setOption(option)


        //3.绑定折现图
        let weekTaskPriorityNum = this.taskStatistics.weekTaskPriorityNum;

        //确定颜色映射关系
        const linePriorityColorMap = {
          '低': '#c4c4c4',
          '中': 'rgb(64, 158, 255)',
          '高': 'rgb(238, 102, 102)',
          '紧急': 'rgb(250, 200, 88)'
        };
        //构建图表数据
        const showLineData = Object.keys(weekTaskPriorityNum).map(key => ({
          data: weekTaskPriorityNum[key],
          name: key,
          type: 'line',
          stack: 'Total',
          lineStyle: {
            color: linePriorityColorMap[key]
          },
          itemStyle: {
            // 这里你可以根据需要设置颜色等样式
            color: linePriorityColorMap[key]
          }
        }));
        option1.series = showLineData
        lineChart.setOption(option1)

      } else {
        this.$message.error("查看任务数据失败！")
      }
    })
    //获取任务表格数据
    this.$request.get("/task/getUserAllTaskByPage", {
      params: {
        userId: this.loginUser.uid,
        currentPage: this.pageNum,
        pageSize: this.pageSize,
        taskStatus: this.tabPosition
      }
    }).then(res => {
      if (res.successFlag) {
        this.tableData = res.data.pageData
        this.total = res.data.totalData
      } else {
        this.$message.error("查看任务失败！")
      }
    })

    //获取所有的项目
    this.$request.get("/project/getAllProject").then(res => {
      if (res.successFlag) {
        this.projectOptions = res.data
      } else {
        this.$message.error("获取所有项目失败！")
      }
    })


  },
  methods: {

    async getUserTaskByPage() {
      await this.$request.get("/task/getUserAllTaskByPage", {
        params: {
          userId: this.loginUser.uid,
          currentPage: this.pageNum,
          pageSize: this.pageSize,
          taskStatus: this.tabPosition
        }
      }).then(res => {
        if (res.successFlag) {
          this.tableData = res.data.pageData
          this.total = res.data.totalData
        } else {
          this.$message.error("查看任务失败！")
        }
      })
    },
    change(pageNum) {
      this.pageNum = pageNum;
      this.taskConditionalQueryByPage();
    },

    async changeTab(queryCriteria) {
      //选择了任务状态作为条件，把分页参数重置
      this.pageNum = 1

      this.tabPosition = queryCriteria
      await this.taskConditionalQueryByPage()
    },
    switchTaskPriority(priorityNum) {
      let reslut = {
        tagStyle: '',
        priorityName: ''
      }
      if (priorityNum === '0') {
        reslut.tagStyle = 'info'
        reslut.priorityName = '低'
        return reslut
      } else if (priorityNum === '1') {
        reslut.tagStyle = ''
        reslut.priorityName = '中'
        return reslut
      } else if (priorityNum === '2') {
        reslut.tagStyle = 'danger'
        reslut.priorityName = '高'
        return reslut
      } else {
        reslut.tagStyle = 'warning'
        reslut.priorityName = '紧急'
        return reslut
      }
      return reslut
    },

    switchTaskType(typeNum) {
      let reslut1 = {
        iconStyle: '',
        typeName: ''
      }
      if (typeNum === 0) {
        reslut1.iconStyle = 'iconfont iconbug'
        reslut1.typeName = 'Bug'
        return reslut1
      } else if (typeNum === 1) {
        reslut1.iconStyle = 'iconfont iconkaifa'
        reslut1.typeName = '开发'
        return reslut1
      } else if (typeNum === 2) {
        reslut1.iconStyle = 'iconfont iconqita'
        reslut1.typeName = '其他'
        return reslut1
      } else if (typeNum === 3) {
        reslut1.iconStyle = 'iconfont iconyouhua'
        reslut1.typeName = '优化'
        return reslut1
      } else if (typeNum === 4) {
        reslut1.iconStyle = 'iconfont iconAPIceshi'
        reslut1.typeName = '测试'
        return reslut1
      }
      return reslut1
    },
    switchTaskStatus(statusNum) {
      //任务状态 （0：创建未处理/1:处理中/2:挂起/3:已完成待测试/4:测试通过/5:测试未通过/6:任务关闭）
      let reslut2 = {
        color: '',
        statusName: ''
      }
      if (statusNum === 0) {
        reslut2.color = '#909399'
        reslut2.statusName = '创建未处理'
        return reslut2
      } else if (statusNum === 1) {
        reslut2.color = '#94c3f3'
        reslut2.statusName = '处理中'
        return reslut2
      } else if (statusNum === 2) {
        reslut2.color = '#E6A23C'
        reslut2.statusName = '挂起'
        return reslut2
      } else if (statusNum === 3) {
        reslut2.color = '#409EFF'
        reslut2.statusName = '已完成待测试'
        return reslut2
      } else if (statusNum === 4) {
        reslut2.color = '#67C23A'
        reslut2.statusName = '测试通过'
        return reslut2
      } else if (statusNum === 5) {
        reslut2.color = '#F56C6C'
        reslut2.statusName = '测试未通过'
        return reslut2
      } else if (statusNum === 6) {
        reslut2.color = '#909399'
        reslut2.statusName = '任务关闭'
        return reslut2
      }
      return reslut2
    },

    //根据项目id去查询项目名称返回展示
    escapeProjectNameById(projectId) {
      this.$request.get("/project/getProjectNameById", {
        params: {
          projectId: projectId
        }
      }).then(res => {
        if (res.successFlag) {
          return res.data
        } else {
          this.$message.error("查看任务失败！")
        }
      })
    },

    //根据所属项目、任务类型、任务级别作为查询条件去查询分页数据
    taskConditionalQueryByPage() {
      this.$request.get("/task/getTaskConditionalQueryByPage", {
        params: {
          userId: this.loginUser.uid,
          currentPage: this.pageNum,
          pageSize: this.pageSize,
          taskStatus: this.tabPosition,
          projectSelectValue: this.projectSelectValue,
          taskTypeSelectValue: this.taskTypeSelectValue,
          taskPrioritySelectValue: this.taskPrioritySelectValue
        }
      }).then(res => {
        if (res.successFlag) {
          this.tableData = res.data.pageData
          this.total = res.data.totalData
        } else {
          this.$message.error("查看任务失败！")
        }
      })
    },

    //查询重置
    conditionReset() {
      //查询条件重置
      this.projectSelectValue = ''
      this.taskTypeSelectValue = ''
      this.taskPrioritySelectValue = ''
      this.tabPosition = 'all'
      this.searchValue=''
      this.taskConditionalQueryByPage()
    },
    //通过id精确匹配和任务名称模糊匹配
    selectTaskByIdOrName() {
      this.$request.get("/task/selectTaskByIdOrName", {
        params: {
          selectValue:this.searchValue,
          userId: this.loginUser.uid,
          currentPage: this.pageNum,
          pageSize: this.pageSize,
          taskStatus: this.tabPosition,
          projectSelectValue: this.projectSelectValue,
          taskTypeSelectValue: this.taskTypeSelectValue,
          taskPrioritySelectValue: this.taskPrioritySelectValue
        }
      }).then(res => {
        if (res.successFlag) {
          this.tableData = res.data.pageData
          this.total = res.data.totalData
        } else {
          this.$message.error("查看任务失败！")
        }
      })
    },

    //查看任务详情，获取此条任务的任务id并跳转”我的任务“模块展示
    viewTaskDetails(taskId){
      // 调用另一个组件的方法
      localStorage.setItem("selectTaskId",taskId)
      this.$router.push('/mytasks')
    }
  }
}
</script>

<style scoped>
.deepBackground {
  display: flex;
  align-items: center;
  justify-content: left;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100vh
}
</style>